from flask import Flask, Blueprint
from flask_cors import CORS

import sys
import logging
sys.path.append("..")
import setting
import mysql_cli
import os
import time
from src.utils.api_util import attach_request_id
from src.api.user import user
from src.api.audit import audit

# 日志配置
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
                    format="%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s - %(message)s",
                    datefmt="%Y-%m-%d %H:%M:%S")
logger = logging.getLogger(__name__)

app = Flask(__name__)
CORS(app)


@app.before_request
def before_request():
    attach_request_id()


api_server = Blueprint('api-server', __name__, url_prefix=f'/api/v1',
                       static_folder='static',
                       template_folder='templates')

# 注册蓝图
blueprints = [user, audit]

for bp in blueprints:
    api_server.register_blueprint(bp)

app.register_blueprint(api_server)

# 加载MySQL
while True:
    try:
        print("连接MySQL...")
        mysql_client = mysql_cli.init_from_conf_file(os.path.join(setting.ROOT_PATH, "mysql.toml"))
        print("连接MySQL成功")
        break
    except Exception as e:
        print("连接MySQL失败, error:", e)
        time.sleep(5)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=6006, debug=True)
